import 'dart:convert';

import 'package:inmotion_pro/extension/future_error_handler.dart';
import 'package:inmotion_pro/http/api_helper.dart';
import 'package:inmotion_pro/http/api_helper_vehicle.dart';
import 'package:inmotion_pro/pages/login_register/area_code/country_model.dart';
import 'package:inmotion_pro/pages/models/http_response/vehicle_info_detail_response_model.dart';
import 'package:inmotion_pro/pages/models/user_model.dart';
import 'package:inmotion_pro/pages/models/vehicle_model.dart';
import 'package:inmotion_pro/service/global_service.dart';
import 'package:inmotion_pro/service/page_cache_service.dart';
import 'package:lx_widgets_library/alert/loading.dart';

mixin HttpRequestMixin {
  /// 缓存的国家/地区列表
  final String countryListKey = "page_data_country_list";

  /// 缓存的车辆信息详情key
  final String vehicleInfoDetail = "page_data_vehicle_info_detail";

  /// 缓存的授权车辆列表key
  final String authorizedVehicleListKey =
      "page_data_authorized_vehicle_list-${GlobalService.to.cacheUserInfo.value.uid}";

  /// 授权车辆的车主列表key
  final String authorizedVehicleOwnersListKey =
      "page_data_authorized_vehicle_owners_list";

  // 是否已经请求过授权车辆列表
  bool _hasRequestedAuthorizedVehicleList = false;

  // 获取国家/地区列表
  httpRequestMixinRequestAreaCodeList(
    // 国家/地区列表回调，是否为缓存回调
    Function((List<AreaCodeModel>, bool)) areaCodeCallback, {
    bool showLoading = true,
    String? sn,
    bool allowHttpRequest = true,
    Function(Exception)? onError,
  }) async {
    PageCacheService.to.getPageData(countryListKey).then((cachedDataModel) {
      if (cachedDataModel != null) {
        // 从缓存中获取车辆列表
        List<AreaCodeModel> areaList =
            (jsonDecode(cachedDataModel.data) as List).map((e) {
          return AreaCodeModel.fromJson(jsonDecode(e) as Map<String, dynamic>);
        }).toList();
        areaCodeCallback((areaList.isEmpty ? [] : areaList, true));
      }
    });
    // 如果不允许HTTP请求，则直接不执行
    if (allowHttpRequest) {
      if (showLoading) {
        Loading.showLoading(null);
      }
      // 获取国家/地区列表
      ApiHelper().getCountryList().then((areaCodeList) {
        if (showLoading) {
          Loading.dismiss();
        }
        // 将vehicleList转换为字符串并保存到缓存
        PageCacheService.to.savePageData(
            pageKey: countryListKey,
            data: jsonEncode(
                areaCodeList.map((e) => jsonEncode(e.toMap())).toList()));
        areaCodeCallback((areaCodeList.isEmpty ? [] : areaCodeList, false));
      }).catchErrorHandler(onError: onError);
    }
  }

  // 请求车辆信息详情
  httpRequestMixinRequestVehicleInfoDetail(
    String sn,
    // 车辆信息详情回调，是否为缓存回调
    Function((VehicleInfoDetailRspModel, bool)) vehicleInfoDetailCallback, {
    bool showLoading = true,
    Function(Exception)? onError,
  }) async {
    final pageKey = "$vehicleInfoDetail-$sn";
    PageCacheService.to.getPageData(pageKey).then((cachedDataModel) {
      if (cachedDataModel != null) {
        // 从缓存中获取车辆列表
        VehicleInfoDetailRspModel vehicleInfo =
            VehicleInfoDetailRspModel.fromJson(
                jsonDecode(cachedDataModel.data) as Map<String, dynamic>);
        vehicleInfoDetailCallback((vehicleInfo, true));
      }
    });
    if (showLoading) {
      Loading.showLoading(null);
    }
    // 获取车辆信息
    ApiHelper().getVehicleInfoDetail(sn).then((rspModel) {
      if (showLoading) {
        Loading.dismiss();
      }
      // 将vehicleList转换为字符串并保存到缓存
      PageCacheService.to
          .savePageData(pageKey: pageKey, data: jsonEncode(rspModel.toMap()));
      vehicleInfoDetailCallback((rspModel, false));
    }).catchErrorHandler(onError: onError);
  }

  // 获取授权车辆列表
  httpRequestMixinRequestAuthorizedVehicleList(
    // 授权车辆列表回调，是否为缓存回调
    Function((List<VehicleModel>, bool)) authorizedVehicleListCallback, {
    bool showLoading = true,
    Function(Exception)? onError,
  }) async {
    PageCacheService.to
        .getPageData(authorizedVehicleListKey)
        .then((cachedDataModel) {
      if (cachedDataModel != null) {
        // 从缓存中获取车辆列表
        List<VehicleModel> vehicleList =
            (jsonDecode(cachedDataModel.data) as List).map((e) {
          return VehicleModel.fromJson(jsonDecode(e) as Map<String, dynamic>);
        }).toList();
        authorizedVehicleListCallback(
            (vehicleList.isEmpty ? [] : vehicleList, true));
      }
    });
    if (showLoading) {
      Loading.showLoading(null);
    }
    // 获取授权车辆列表
    ApiHelper().getAuthorizedVehicleList().then((rspModelList) {
      if (showLoading) {
        Loading.dismiss();
      }
      _hasRequestedAuthorizedVehicleList = true;
      // 将vehicleList转换为字符串并保存到缓存
      PageCacheService.to.savePageData(
          pageKey: authorizedVehicleListKey,
          data: jsonEncode(
              rspModelList.map((e) => jsonEncode(e.toMap())).toList()));
      authorizedVehicleListCallback(
          (rspModelList.isEmpty ? [] : rspModelList, false));
    }).catchErrorHandler(onError: onError);
  }

  // 请求授权车辆列表，如果已经请求过则直接返回缓存
  Future<List<VehicleModel>>
      httpRequestMixinOnlyRequestAuthorizedVehicleList() {
    if (_hasRequestedAuthorizedVehicleList) {
      // 已经请求过，直接返回缓存的车辆列表
      return PageCacheService.to
          .getPageData(authorizedVehicleListKey)
          .then((cachedDataModel) {
        if (cachedDataModel != null) {
          // 从缓存中获取车辆列表
          List<VehicleModel> vehicleList =
              (jsonDecode(cachedDataModel.data) as List).map((e) {
            return VehicleModel.fromJson(jsonDecode(e) as Map<String, dynamic>);
          }).toList();
          return Future.value(vehicleList.isEmpty ? [] : vehicleList);
        }
        return Future.value([]);
      });
    } else {
      // 获取授权车辆列表
      return ApiHelper().getAuthorizedVehicleList().then((rspModelList) {
        _hasRequestedAuthorizedVehicleList = true;
        // 将vehicleList转换为字符串并保存到缓存
        PageCacheService.to.savePageData(
            pageKey: authorizedVehicleListKey,
            data: jsonEncode(
                rspModelList.map((e) => jsonEncode(e.toMap())).toList()));
        return Future.value(rspModelList);
      });
    }
  }

  // 获取授权车辆的车主列表
  httpRequestMixinRequestAuthorizedUserList(
    String sn,
    // 车主列表回调，是否为缓存回调
    Function((List<UserModel>, bool)) userListCallback, {
    bool showLoading = true,
    Function(Exception)? onError,
  }) async {
    final pageKey = "$authorizedVehicleOwnersListKey-$sn";
    PageCacheService.to.getPageData(pageKey).then((cachedDataModel) {
      if (cachedDataModel != null) {
        // 从缓存中获取车辆列表
        List<UserModel> userList =
            (jsonDecode(cachedDataModel.data) as List).map((e) {
          return UserModel.fromMap(jsonDecode(e) as Map<String, dynamic>);
        }).toList();
        userListCallback((userList.isEmpty ? [] : userList, true));
      }
    });

    if (showLoading) {
      Loading.showLoading(null);
    }
    // 获取授权车辆的车主列表
    ApiHelper().getVehicleAuthorizedOwners(sn).then((userList) {
      if (showLoading) {
        Loading.dismiss();
      }
      // 将userList转换为字符串并保存到缓存
      PageCacheService.to.savePageData(
          pageKey: pageKey,
          data:
              jsonEncode(userList.map((e) => jsonEncode(e.toMap())).toList()));
      userListCallback((userList.isEmpty ? [] : userList, false));
    }).catchErrorHandler(onError: onError);
  }
}
